// @ts-nocheck
import request from '@system.request'
import utils from '../helper/utils';
import ajax from './ajax';
import prompt from '@system.prompt';
import config from '../config';


/**
 * 单词文字识别
 * @param {string} uri 图片地址
 * @returns 识别到的字符结果（数组格式）
 */
async function textRecognition(uri) {
    return new Promise((resolve, reject) => {
        request.upload({
            url: `${config.API_HOST}/ocr`,
            files: [
                {
                    uri,
                    name: 'file',
                    filename: 'test.png'
                }
            ],
            data: [{
                name: 'detect_direction',
                value: false
            }],
            success: function (res) {
                const data = JSON.parse(res.data).data;
                /**
                 * 
                 {
    "words_result": [
        {
            "location": {
                "top": 766,
                "left": 492,
                "width": 604,
                "height": 442
            },
            "words": "apple"
        },
        {
            "location": {
                "top": 806,
                "left": 1513,
                "width": 605,
                "height": 390
            },
            "words": "orange"
        },
        {
            "location": {
                "top": 764,
                "left": 2545,
                "width": 550,
                "height": 279
            },
            "words": "alone"
        },
        {
            "location": {
                "top": 1384,
                "left": 529,
                "width": 558,
                "height": 378
            },
            "words": "happy"
        },
        {
            "location": {
                "top": 1286,
                "left": 1587,
                "width": 701,
                "height": 336
            },
            "words": "another"
        },
        {
            "location": {
                "top": 1343,
                "left": 2696,
                "width": 617,
                "height": 382
            },
            "words": "morning"
        }
    ],
    "words_result_num": 6,
    "log_id": "1774690372645064332"
}
                 
                 */
                const { words_result, words_result_num, error_code, error_msg } = data;
                if (error_code) {
                    reject({ err_no: error_code, err_msg: error_msg });
                } else if (words_result_num > 0) {
                    resolve(words_result[0].words.replace(/ /g, ""));
                } else {
                    reject({ err_no: 10002, err_msg: '无法识别，请重新输入' });
                }
            },
            fail: function (data, code) {
                reject({ err_no: code, err_msg: data });
            }
        })
    });
}

export default textRecognition;
